import java.util.ArrayList;
import java.util.List;
import java.util.Date;

public class UserService {
    private List<User> users = new ArrayList<>();
    private Integer nextId = 1;

    public UserService() {
        initializeSampleUsers();
    }

    private void initializeSampleUsers() {
        users.add(new User(nextId++, "admin", "admin123", "ADMIN", "admin@estore.com", new Date()));
        users.add(new User(nextId++, "user1", "user123", "USER", "user1@estore.com", new Date()));
    }

    public User register(String username, String password, String email) {
        if (users.stream().anyMatch(u -> u.getUsername().equals(username))) {
            return null;
        }

        User user = new User(nextId++, username, password, "USER", email, new Date());
        users.add(user);
        return user;
    }

    public User login(String username, String password) {
        return users.stream()
                .filter(u -> u.getUsername().equals(username) && u.getPassword().equals(password))
                .findFirst()
                .orElse(null);
    }

    public User findById(Integer id) {
        return users.stream()
                .filter(u -> u.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    public boolean isAdmin(Integer userId) {
        User user = findById(userId);
        return user != null && "ADMIN".equals(user.getRole());
    }
}